package com.caine.multithread;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

/**
 * @Author: CaineZhu
 * @Description:
 * @Date: Created in 16:16 2020/12/22
 * @Modified By:
 */
public class CompletableFutureTest {
    public static void main(String[] args) throws Exception {
        System.out.println("11111111 " + System.currentTimeMillis());
        //有返回值
        CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
            try {
                TimeUnit.SECONDS.sleep(2);
                System.out.println("run run run");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "test";
        }).whenComplete((ret, action) -> System.out.println("ret:" + ret)).exceptionally((e) -> {
            System.out.println(e.getMessage());
            return null;
        }).thenApply((ret)->ret+"thenApply");
        //获取结果时依然是同步的
        String s = future.get();
        System.out.println("s = " + s);
        //无返回值
        CompletableFuture<Void> future2 = CompletableFuture.runAsync(() -> System.out.println("run2 run2 run2"));
    }
}
